import QQMapWX from "./sdk/qqmap-wx-jssdk.min.js";
const formatTime = (_Date, format) => {
	if (!_Date) {
		return "";
	}
	var date = new Date(_Date);
	return commonDate(date, format);
};
const commonDate = (date, format) => {
	var formateArr = ["Y", "M", "D", "h", "m", "s"];
	var returnArr = [];
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));
	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));
	var timeStr = format;
	for (var i = 0; i < formateArr.length; i++) {
		timeStr = timeStr.replace(formateArr[i], returnArr[i]);
	}
	return timeStr;
};
const formatNumber = (n) => {
	const s = n.toString();
	return s[1] ? s : "0" + s;
};

const getLocationInfo = () => {
	return new Promise((resolve) => {
		let location = {
			longitude: 0,
			latitude: 0,
			province: "",
			city: "",
			area: "",
			street: "",
			address: "",
			formatted_addresses: "",
		};
		// 使用uni.getLocation获取经纬度
		uni.getLocation({
			type: "gcj02",
			isHighAccuracy: true,
			success(res) {
				location.longitude = res.longitude;
				location.latitude = res.latitude;
				// 创建实例
				const qqmapsdk = new QQMapWX({
					key: "DMCBZ-PC3EV-UIFPY-5AMGT-LPUTK-PAFWP", //这里填写自己申请的key
				});
				// 使用腾讯的逆地址解析
				qqmapsdk.reverseGeocoder({
					location,
					success(response) {
						let info = response.result;
						location.province = info.address_component.province;
						location.city = info.address_component.city;
						location.area = info.address_component.district;
						location.street = info.address_component.street;
						location.address = info.address;
						location.formatted_addresses =
							info.formatted_addresses.standard_address;
						location.longitude = info.location.lat;
						location.latitude = info.location.lng;
						resolve(location);
					},
					fail(err) {
						resolve(location);
					},
				});
			},
			fail(err) {
				resolve(location);
			},
		});
	});
};

const chooseLocationInfo = () => {
	return new Promise((resolve) => {
		uni.chooseLocation({
			success: (res) => {
				resolve(res);
			},
			fail: () => {
				uni.getSetting({
					success: (res) => {
						var status = res.authSetting;
						if (!status["scope.userLocation"]) {
							uni.showModal({
								title: "是否授权当前位置",
								content: "需要获取您的地理位置，请确认授权",
								success: (tip) => {
									if (tip.confirm) {
										uni.openSetting({
											success: (data) => {
												if (data.authSetting["scope.userLocation"] === true) {
													uni.showToast({
														title: "授权成功",
														icon: "success",
														duration: 1000,
													});
													uni.chooseLocation({
														success: (res) => {
															resolve(res);
														},
													});
												} else {
													uni.showToast({
														title: "授权失败",
														icon: "none",
														duration: 1000,
													});
												}
											},
										});
									}
								},
							});
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "授权失败",
							icon: "none",
							duration: 1000,
						});
					},
				});
			},
		});
	});
};

const addParamsToURL = (params) => {
	// 将参数对象转换为查询字符串
	const queryString = Object.keys(params)
		.filter((key) => !!params[key])
		.map(
			(key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
		)
		.join("&");
	return `${queryString}`;
};
const convertMonthsToYearsAndMonths = (months) => {
	console.log(months);
	if (isNaN(months) || months < 0) {
		return months;
	}
	console.log(months);
	months = Number(months);
	const years = Math.floor(months / 12);
	const remainingMonths = months % 12;
	if (years === 0) {
		return `${remainingMonths}个月`;
	} else if (remainingMonths === 0) {
		return `${years}年`;
	} else {
		return `${years}年${remainingMonths}个月`;
	}
};

const formatMessageDate = (messageDate) => {
	const messageDateTime = new Date(messageDate);
	const today = new Date();

	if (messageDateTime.toDateString() === today.toDateString()) {
		return messageDateTime.getHours() + ':' + messageDateTime.getMinutes();
	} else {
		const yesterday = new Date(today);
		yesterday.setDate(yesterday.getDate() - 1);

		if (messageDateTime.toDateString() === yesterday.toDateString()) {
			return '昨天';
		} else if (messageDateTime.getFullYear() === today.getFullYear()) {
			return (messageDateTime.getMonth() + 1) + '-' + messageDateTime.getDate();
		} else {
			return messageDateTime.getFullYear() + '-' + (messageDateTime.getMonth() + 1) + '-' + messageDateTime.getDate();
		}
	}
}

const checkSubscribe = (ids = []) => {
	return new Promise((resolve) => {
		uni.requestSubscribeMessage({
			tmplIds: ids, // 需要订阅的模板消息ID列表
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				resolve(err)
			}
		})
	})
}

module.exports = {
	formatTime,
	getLocationInfo,
	addParamsToURL,
	chooseLocationInfo,
	convertMonthsToYearsAndMonths,
	formatMessageDate,
	checkSubscribe
};